import { ref, watch } from 'vue'
export default class SliderVerify {
  constructor(from) {
    let options = Object.assign(
      {
        x: 0,
        y: from.py
      },
      from
    )

    this.options = ref(options)
    this.init()
  }
  init() {
    let options = this.options.value
    this.btnStyle = ref({
      transform: `translatex(${options.x}px)`
    })
    this.maskPic = ref({
      width: options.pic_w + 'px',
      height: options.pic_h + 'px',
      transform: `translate(-${options.px}px,-${options.py}px)`
    })
    this.originPic = ref({
      width: options.pic_w + 'px',
      height: options.pic_h + 'px'
    })
    this.maskStyle = ref({
      width: options.mask_w + 'px',
      height: options.mask_h + 'px',
      transform: `translate(${options.x}px,${options.y}px)`
    })
    this.containerStyle = ref({
      width: options.pic_w + 'px'
    })

    watch(
      this.options,
      (newValue) => {
        let x = newValue.x
        let y = newValue.y
        x = x < 0 ? 0 : x
        let max_x = newValue.pic_w - newValue.mask_w
        x = x > max_x ? max_x : x
        this.btnStyle.value = {
          transform: `translatex(${x}px)`
        }
        this.maskStyle.value.transform = `translate(${x}px,${y}px)`
      },
      {
        deep: true
      }
    )
  }
  onMove(e) {
    if (this.isStart) {
      e = this.getTouch(e)
      let nx = e.clientX
      let dx = nx - this.ox
      this.options.value.x = this.originX + dx
    }
  }
  getTouch(e) {
    return e.touches[0]
  }
  onStart(e) {
    e = this.getTouch(e)
    this.isStart = true
    this.ox = e.clientX
    this.originX = this.options.value.x
  }
  onEnd(e) {
    this.isStart = false
    this.check()
  }
  check() {
    let options = this.options.value
    let diff = options.x - options.px
    if (Math.abs(diff) <= 1) {
      options.onCheck(true)
    } else {
      options.onCheck(false)
      this.options.value.x = 0
    }
  }
}
